import json
from sqlalchemy import or_
from application.apps.users.models import User
from application import db, redis
from flask import current_app

class DataNotExists(Exception):
    """数据不存在"""
    pass

class DataSaveError(Exception):
    """数据缓存出错"""
    pass

def check_user_mobile(mobile):
    return User.query.filter(User.mobile == mobile).first()

def check_user_by_account(account):
    return User.query.filter(or_(
        User.mobile == account,
        User.name == account,
        User.email == account
    )).first()

def save_user_data(data):
    instance = User(**data)
    db.session.add(instance)
    db.session.commit()

def save_user_data_to_cache(user_data):
    """缓存用户信息"""
    json_data = json.dumps(user_data)
    try:
        redis.setex(f"user_{user_data['id']}",current_app.config["USER_LOGIN_CACHE"],json_data)
    except Exception:
        raise DataSaveError

def get_data_by_cache(key):
    data = redis.get(key)
    if data is None:
        raise DataNotExists

    # python从redis中提取的数据最终都是bytes类型，所以需要进行编码处理
    return data.decode()

def delete_data_by_cache(key):
    redis.delete(key)


